import os
import subprocess

import mimetypes

from damn.transcoder import TranscoderFailedException, BaseTranscoder


def RunSND2PNG(anURIin, anURIout, size=(256, 256)):
  b = os.path.abspath(os.path.join(os.path.dirname(__file__), 'snd2png.sh'))
  args = [b, anURIin, anURIout, str(size[0]), str(size[1])]
  try:
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    s, t = p.communicate()
  except OSError:
    print("E: RunSND2PNG failed!", s, t)
  if p and p.returncode != 0:
    print("E: RunSND2PNG failed with error code %d! "%(p.returncode), t)
  return p.returncode, s, t     

    
class SoundImageTranscoder(BaseTranscoder):
  transcoder = True
  convert_map = {"video/mp4" : ["image/png"], 
                  "audio/ogg" : ["image/png"],
                  "audio/mpeg" : ["image/png"],}
  _options = [('sizex', int, 256), ('sizey', int, 256),]
  options_map = {"video/mp4" : _options,
                 "audio/ogg" : _options, 
                 "audio/mpeg" : _options,}
  
  def transcode(self, anAssetReference, dstFormat, **kwargs):  
    filePath = super(SoundImageTranscoder, self).transcode(anAssetReference, dstFormat, kwargs)
    
    returncode, s, t = RunSND2PNG(anAssetReference.file.fileName, filePath, (kwargs['sizex'], kwargs['sizey'],) )
    print s,t 
    if returncode != 0: raise TranscoderFailedException('SoundImageTranscoder failed! (return code %d) %s %s'%(returncode, s, t))
    return filePath

